package com.hengjun.baccarat;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hengjun.baccarat.net.Server;
import com.hengjun.baccarat.net.UpdateManager;
import com.hengjun.baccarat.net.UrlConn;
import com.hengjun.baccarat.pojo.GlobalService;
import com.hengjun.baccarat.pojo.ViewDataObject;
import com.hengjun.baccarat.utils.DrawForm;
import com.hengjun.baccarat.utils.DrawFourForm;
import com.hengjun.baccarat.utils.DrawThreeForm;
import com.hengjun.baccarat.utils.DrawTwoForm;
import com.hengjun.baccarat.utils.GetJSON;
import com.hengjun.baccarat.utils.RecordCore;
import com.hengjun.baccarat.utils.ThreadManager;

public class Activity_Map extends Activity {
	private DrawForm form1;
	private DrawTwoForm form2;
	private DrawThreeForm form3;
	private DrawFourForm form4;
	private boolean isExitt = false;
	private Thread uploadThread;
	private ProgressDialog dialog;
	private AutoUpLoadThead autoUpLoadThead;
	private HorizontalScrollView scrollView1;
	private HorizontalScrollView scrollView2;
	private HorizontalScrollView scrollView3;
	private HorizontalScrollView scrollView4;
	private InputMethodManager inputManager;
	private Button revocation;
	private TextView benjinText;
	private UpdateManager update = new UpdateManager(this);

	private TextView danbianhaoView;
	private TextView addMoneyText;
	private TextView benjinView;
	private String[] list = new String[] {};
	private double backMoney = 0d;

	private boolean show = true;
	private List<RecordCore> rcList = GlobalService.list;

	public static double addMoney = 0d;
	private String bettingResult = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_map);
		ThreadManager.handler = new testHander();
		addMoney = getIntent().getExtras().getDouble("addMoney");
		bettingResult = getIntent().getExtras().getString("bettingResult");
		list = getIntent().getExtras().getStringArray("list");
		Server.SERVER.context = Activity_Map.this;

		initView();
		autoUpLoadThead = new AutoUpLoadThead();
//		autoUpLoadThead.start();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	private void initView() {
		form1 = (DrawForm) findViewById(R.id.form1);
		form2 = (DrawTwoForm) findViewById(R.id.form2);
		form3 = (DrawThreeForm) findViewById(R.id.form3);
		form4 = (DrawFourForm) findViewById(R.id.form4);

		scrollView1 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView1);
		scrollView2 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView2);
		scrollView3 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView3);
		scrollView4 = (HorizontalScrollView) findViewById(R.id.horizontalScrollView4);
		scrollView2.setVisibility(View.INVISIBLE);
		scrollView3.setVisibility(View.INVISIBLE);
		scrollView4.setVisibility(View.INVISIBLE);

		danbianhaoView = (TextView) findViewById(R.id.danbianhaoView);
		addMoneyText = (TextView) findViewById(R.id.addMoneyText);
		danbianhaoView.setText(rcList.get(OrderList.point).getRecordsn());
		benjinView = (TextView) findViewById(R.id.benjinView);
		benjinText = (TextView) findViewById(R.id.benjinText);
		revocation = (Button) findViewById(R.id.revocation);
		if (Activity_Control.captial < 0) {
			benjinView.setTextColor(Color.RED);
			double captial = Activity_Control.captial;
			benjinView.setText(GlobalService.getDoubleString(captial));
		} else {
			benjinView.setTextColor(Color.BLACK);
			benjinView.setText(GlobalService
					.getDoubleString(Activity_Control.captial));
		}
		benjinText.setText(list[3]);
		double _addMoney = Activity_Control.totalAddMoney;
		addMoneyText.setText(GlobalService.getDoubleString(_addMoney));
	}

	public void mapSwitch(View v) {
		if (show == true) {
			scrollView1.setVisibility(View.INVISIBLE);
			scrollView3.setVisibility(View.VISIBLE);
			scrollView2.setVisibility(View.VISIBLE);
			scrollView4.setVisibility(View.VISIBLE);
			show = false;
		} else {
			scrollView1.setVisibility(View.VISIBLE);
			scrollView3.setVisibility(View.INVISIBLE);
			scrollView2.setVisibility(View.INVISIBLE);
			scrollView4.setVisibility(View.INVISIBLE);
			show = true;
		}
	}

	private Dialog reOpenDialog = null;

	public void reOpenListener(View v) {
		reOpenDialog = new Dialog(this, R.style.MyDialogStyle);
		reOpenDialog.setContentView(R.layout.reopen_dialog);
		Button detemind = (Button) reOpenDialog.findViewById(R.id.button2);
		Button cancel = (Button) reOpenDialog.findViewById(R.id.button1);
		detemind.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				reOpenDialog.dismiss();
				autoUpLoadThead.setCode("-1");
				uploadThread = new Thread(resetRun);
				uploadThread.start();
			}
		});
		cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				reOpenDialog.dismiss();
			}
		});
		reOpenDialog.show();
	}

	public void revocationListener(View v) {
		autoUpLoadThead.setCode("-1");
		uploadThread = new Thread(run2);
		uploadThread.start();
	}

	public void buttonListener(View v) {
		Activity_Control.tempmap.put("addMoney", Activity_Control.addMoney);
		Activity_Control.tempmap.put("captial", Activity_Control.captial);
		autoUpLoadThead.setCode("-1");
//		autoUpLoadThead.interrupt();
		Activity_Map.this.finish();
	}

	public void uploadListener(View v) {
		try {
			autoUpLoadThead.setCode("-1");
		} catch (Exception e) {
			e.printStackTrace();
		}
		uploadThread = new Thread(run);
		uploadThread.start();
	}

	private Dialog addMoneyDialog = null;

	public void addMoneyListener(View v) {
		addMoneyDialog = new Dialog(this, R.style.MyDialogStyle);
		addMoneyDialog.setContentView(R.layout.addmoney_dialog);
		Button detemin = (Button) addMoneyDialog.findViewById(R.id.button1);
		Button cancel = (Button) addMoneyDialog.findViewById(R.id.button2);
		final EditText moneyText = (EditText) addMoneyDialog
				.findViewById(R.id.editText1);
		inputManager = (InputMethodManager) getSystemService(Activity_Map.INPUT_METHOD_SERVICE);
		inputManager.showSoftInput(moneyText, InputMethodManager.RESULT_SHOWN);
		inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,
				InputMethodManager.HIDE_IMPLICIT_ONLY);

		detemin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				inputManager.hideSoftInputFromWindow(
						moneyText.getWindowToken(), 0);
				addMoneyDialog.dismiss();
				String getRusult = moneyText.getText().toString();
				if (!getRusult.equals("")) {
					double transform = Double.parseDouble(getRusult);
					addMoney += Double.parseDouble(GlobalService
							.getDoubleString(transform));

					String benjinTextstr = benjinView.getText().toString();
					if (benjinTextstr.equals("")) {
						benjinTextstr = "0";
					} else {
						Activity_Control.captial = Double
								.parseDouble(benjinTextstr) + addMoney;
						Activity_Control.tempmap.put("captial",
								Activity_Control.captial);
						Activity_Control.addMoney = addMoney;
						Activity_Control.totalAddMoney = addMoney
								+ Activity_Control.totalAddMoney;
					}
					benjinView.setText(GlobalService.getDoubleString(Double
							.parseDouble(benjinTextstr) + addMoney));
					addMoneyText.setText(GlobalService.getDoubleString(Double
							.parseDouble(addMoneyText.getText().toString())
							+ Double.parseDouble(getRusult)));
					Activity_Control.tempmap.put("totalAddMoney", Double
							.parseDouble(addMoneyText.getText().toString()));

				}
			}
		});
		cancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				inputManager.hideSoftInputFromWindow(
						moneyText.getWindowToken(), 0);
				addMoneyDialog.dismiss();
			}
		});
		addMoneyDialog.show();
	}
	private boolean isAutoUploadFlag=false;
	class AutoUpLoadThead extends Thread {
		boolean flag = false;
		private String code = "";

		@Override
		public void run() {
			while (true) {
				try {
					String code = getCode();
					if (code.equals("")) {
						handler.obtainMessage(7).sendToTarget();
						isAutoUploadFlag=false;
						uploadData();
						isAutoUploadFlag=true;
						handler.obtainMessage(8).sendToTarget();
						Thread.sleep(60000*3);
					}
				} catch (Exception e) {
					e.printStackTrace();
					handler.obtainMessage(8).sendToTarget();
					break;
				}
			}
		}

		public synchronized String getCode() {
			while (flag) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
					Toast.makeText(Activity_Map.this, "程序發生錯誤退出",
							Toast.LENGTH_SHORT).show();
				}
			}
			return code;
		}

		public synchronized void setCode(String code) {

			if (code.equals("")) {
				flag = false;
				this.notify();
				this.code = code;
			} else {
				flag = true;
			}

		}
	}

	private Runnable run = new Runnable() {

		@Override
		public void run() {

			// TODO Auto-generated method stub
			handler.obtainMessage(7).sendToTarget();
			try {
				handler.obtainMessage(1).sendToTarget();
				uploadData();
				handler.obtainMessage(2).sendToTarget();
				handler.obtainMessage(8).sendToTarget();
			} catch (Exception e) {
				handler.obtainMessage(8).sendToTarget();
				handler.obtainMessage(3).sendToTarget();
				e.printStackTrace();
			}
			autoUpLoadThead.setCode("");
			if (isExitt) {
				handler.obtainMessage(6).sendToTarget();
			}
		}
	};

	private synchronized void uploadData() {
		try {
			
			String result = UrlConn.queryPort(list[1]);
			if (result != null && !result.equals("-1")) {
				GlobalService.upLoad(list[1], bettingResult);

			} else {
				GlobalService.list = UrlConn.RecordConn();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			handler.obtainMessage(11).sendToTarget();
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		update.closeUpdate();
		if (reOpenDialog != null) {
			reOpenDialog.dismiss();
		}
		if (addMoneyDialog != null) {
			addMoneyDialog.dismiss();
		}
		if (controlError != null) {
			controlError.dismiss();
		}
		if (userError != null) {
			userError.dismiss();
		}
		if (netError != null) {
			netError.dismiss();
		}
	}

	private Dialog netUploadError = null;
	private Dialog controlError = null;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			if (msg.what == 0) {
				controlError = new Dialog(Activity_Map.this,
						R.style.MyDialogStyle);
				controlError.setContentView(R.layout.erro_dialog);
				TextView message = (TextView) controlError
						.findViewById(R.id.textView1);
				message.setText("不能操作該單號!");
				Button exit = (Button) controlError.findViewById(R.id.button1);
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						controlError.dismiss();
//						autoUpLoadThead.interrupt();
						Intent _intent = new Intent(Activity_Map.this,
								OrderList.class);
						Activity_Map.this.startActivity(_intent);
						Activity_Map.this.finish();
					}
				});
				controlError.show();
			}
			if (msg.what == 1) {
				try {
					dialog = Login.createProgressDialog(Activity_Map.this,
							"上傳數據");
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			if (msg.what == 2) {
				revocation.setEnabled(true);
				try {
					dialog.dismiss();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			if (msg.what == 3) {
				netUploadError = new Dialog(Activity_Map.this,
						R.style.MyDialogStyle);
				netUploadError.setContentView(R.layout.erro_dialog);
				TextView message = (TextView) netUploadError
						.findViewById(R.id.textView1);
				message.setText("網絡故障,上傳失敗!");
				Button exit = (Button) netUploadError
						.findViewById(R.id.button1);
				exit.setText("退出");
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						netUploadError.dismiss();
						Activity_Map.this.finish();
					}
				});
				netUploadError.show();
			}

			if (msg.what == 4) {
				revocation.setEnabled(false);
				dialog = Login.createProgressDialog(Activity_Map.this, "正在撤銷");
			}
			if (msg.what == 5) {
				form1.invalidate();
				form2.invalidate();
				form3.invalidate();
				form4.invalidate();
			}
			if (msg.what == 6) {
//				autoUpLoadThead.interrupt();
				Activity_Map.this.finish();
			}
			if (msg.what == 10) {
				if (backMoney != 0) {
					String benjinstr = benjinView.getText().toString();
					double captial = Double.parseDouble(benjinstr) - backMoney;
					Activity_Control.tempmap.put("captial", captial);
					Activity_Control.captial = captial;
					benjinView.setText(GlobalService.getDoubleString(captial));
				}
				double _addMoney = Double.parseDouble(addMoneyText.getText()
						.toString()) - backAddMoney;
				Activity_Control.tempmap.put("totalAddMoney", _addMoney);
				addMoneyText.setText(GlobalService.getDoubleString(_addMoney));
				backMoney = 0;
			}
			if (msg.what == 11) {
				if (dialog != null) {
					dialog.dismiss();
				}
				netUploadError = new Dialog(Activity_Map.this,
						R.style.MyDialogStyle);
				netUploadError.setContentView(R.layout.erro_dialog);
				TextView message = (TextView) netUploadError
						.findViewById(R.id.textView1);
				message.setText("網絡異常!");
				Button exit = (Button) netUploadError
						.findViewById(R.id.button1);
				exit.setText("返回");
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						netUploadError.dismiss();
					}
				});
				netUploadError.show();
			}
			if (msg.what == 12) {
				form1.invalidate();
				form2.invalidate();
				form3.invalidate();
				form4.invalidate();
			}
			if (msg.what == 13) {
				Toast.makeText(Activity_Map.this, "自動上傳中，請稍後...",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	private Runnable resetRun = new Runnable() {
		@Override
		public void run() {
//			if(isAutoUploadFlag){
				
				// TODO Auto-generated method stub
				handler.obtainMessage(7).sendToTarget();
				try {
					handler.obtainMessage(1).sendToTarget();
					uploadData();
					ViewDataObject.resetViewData();
					autoUpLoadThead.setCode("-1");
					uploadData();
					handler.obtainMessage(12).sendToTarget();
					handler.obtainMessage(2).sendToTarget();
				} catch (Exception e) {
					handler.obtainMessage(12).sendToTarget();
					handler.obtainMessage(3).sendToTarget();
					e.printStackTrace();
				}
				autoUpLoadThead.setCode("");
				if (isExitt) {
					handler.obtainMessage(6).sendToTarget();
				}
//			}
//			else{
//				handler.obtainMessage(13).sendToTarget();
//			}
		
		}

	};
	private Dialog netError = null;
	private Dialog userError = null;

	@SuppressLint("HandlerLeak")
	private class testHander extends Handler {
		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 0) {
				userError = new Dialog(Activity_Map.this, R.style.MyDialogStyle);
				userError.setContentView(R.layout.erro_dialog);
				ImageView image = (ImageView) userError
						.findViewById(R.id.imageView1);
				image.setImageResource(R.drawable.confirm_dialog_failweb);
				TextView message = (TextView) userError
						.findViewById(R.id.textView1);
				message.setText("退出提示,賬戶異地登陸!");
				Button exit = (Button) userError.findViewById(R.id.button1);
				exit.setText("退出");
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						userError.dismiss();
//						autoUpLoadThead.interrupt();
						Intent _intent = new Intent(Activity_Map.this,
								Login.class);
						Activity_Map.this.startActivity(_intent);
						Activity_Map.this.finish();
					}
				});
				userError.show();
			}
			// 更新
			if (msg.what == 1001) {
				update.showNoticeDialog();
			}
			if (msg.what == 500) {
				netError = new Dialog(Activity_Map.this, R.style.MyDialogStyle);
				netError.setContentView(R.layout.erro_dialog);
				TextView message = (TextView) netError
						.findViewById(R.id.textView1);
				message.setText("網絡連接故障!");
				Button exit = (Button) netError.findViewById(R.id.button1);
				exit.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						netError.dismiss();
						Intent _intent = new Intent(Activity_Map.this,
								Login.class);
						Activity_Map.this.startActivity(_intent);
						Activity_Map.this.finish();
					}
				});
				netError.show();
			}
		}
	}

	private double backAddMoney = 0d;

	private Runnable run2 = new Runnable() {
		@Override
		public void run() {
			String result;
			try {
				result = UrlConn.queryPort(list[1]);
				if (ViewDataObject.getViewDataObject().getBigStreetArrayList()
						.size() != 0) {
					if (result != null && !result.equals("-1")) {

						double temobackMoney = UrlConn.getBackMoney();
						List<String> bettingList = ViewDataObject
								.getViewDataObject().getBettingResultList();
						if (bettingList.size() > 0) {

							String[] str = bettingList.get(
									bettingList.size() - 1).split(",");
							String backStr = "";
							String backStrAddMoney = "";
							for (String s : str) {

								String key = s.replaceAll("[{]", "")
										.replaceAll("[}]", "").split(":")[0];
								String value = s.replaceAll("[{]", "")
										.replaceAll("[}]", "").split(":")[1];
								if (key.equals("\"resultWin\"")) {
									backStr = value + "";
								}
								if (key.equals("\"addMoney\"")) {
									backStrAddMoney = value + "";
								}

							}
							backAddMoney = Double.parseDouble(backStrAddMoney
									.toString());
							backMoney = Double.parseDouble(backStr.toString())
									+ Double.parseDouble(backStrAddMoney
											.toString());
						} else {
							backMoney = temobackMoney;
						}
						handler.obtainMessage(10).sendToTarget();
						GlobalService.back();
						try {
							List<Object> bigStreet = ViewDataObject
									.getViewDataObject()
									.getBigStreetArrayList();
							String bigStreetStr = GetJSON
									.getListJson(bigStreet);
							if (bigStreetStr.equals("")) {
								handler.obtainMessage(4).sendToTarget();
								GlobalService.upLoad(list[1], "backNull");
								UrlConn.ListQuery(list[1] + "");
								handler.obtainMessage(2).sendToTarget();
							}

						} catch (Exception e) {
							e.printStackTrace();
							handler.obtainMessage(2).sendToTarget();
							handler.obtainMessage(3).sendToTarget();
						}
					} else {
						try {
							GlobalService.list = UrlConn.RecordConn();
							handler.obtainMessage(0).sendToTarget();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							handler.obtainMessage(3).sendToTarget();
						}
					}
				} else {
					if (result != null && !result.equals("-1")) {
						handler.obtainMessage(4).sendToTarget();
						try {
							GlobalService.upLoad(list[1], "null");
							UrlConn.ListQuery(list[1] + "");
							handler.obtainMessage(2).sendToTarget();
						} catch (Exception e) {
							handler.obtainMessage(2).sendToTarget();
							e.printStackTrace();
							handler.obtainMessage(3).sendToTarget();
						}
					} else {
						try {
							GlobalService.list = UrlConn.RecordConn();
							handler.obtainMessage(0).sendToTarget();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							handler.obtainMessage(3).sendToTarget();
						}
					}
				}
				autoUpLoadThead.setCode("");
				handler.obtainMessage(5).sendToTarget();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				handler.obtainMessage(11).sendToTarget();
			}

		}
	};

}
